package com.adinnet.api.common.controller;

import com.adinnet.api.common.form.UploadForm;
import com.adinnet.common.upload.UploadUtils;
import com.adinnet.common.utils.Collections3;
import com.adinnet.core.JsonResult;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author: sunjianbo
 * @date: 2019/8/8 18:58
 */
@RestController
@RequestMapping("/api/v1/upload")
public class UploadController extends ApiController {

    /**
     * 上传文件
     *
     * @param imgFile
     * @return
     */
    @PostMapping("/uploadFile")
    public JsonResult uploadManyFile(@RequestParam(value = "imgFile", required = false) MultipartFile[] imgFile) {
        if (null == imgFile && imgFile.length == 0) {
            return JsonResult.error("文件必传");
        }
        StringBuffer sb = new StringBuffer();
        for (MultipartFile multipartFile : imgFile) {
            String path = UploadUtils.uploadFile(multipartFile);
            if (sb.toString().isEmpty()) {
                sb.append(path);
            } else {
                sb.append(",").append(path);
            }
        }
        return JsonResult.ok().put("data",sb.toString());
    }

    /**
     * base64转文件并上传
     *
     * @param uploadForm
     * @return
     */
    @PostMapping("/uploadBase64")
    public R uploadBase64(@RequestBody UploadForm uploadForm) {
        if (Collections3.isEmpty(uploadForm.getBase64s())) {
            return failed("base64必传");
        }
        StringBuffer sb = new StringBuffer();
        for (String base64 : uploadForm.getBase64s()) {
            String path = UploadUtils.uploadBase64(base64);
            if (sb.toString().isEmpty()) {
                sb.append(path);
            } else {
                sb.append(",").append(path);
            }
        }
        return success(sb.toString());
    }
}
